﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.Security.Cryptography.Xml;
using System.Transactions;
using ZenSystemService.Api.Business;
using ZenSystemService.Api.Common;
using ZenSystemService.Api.Common.Auth;
using ZenSystemService.Api.Common.Encryption;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.Entities;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Controllers
{
    [Route("api/trainees")]
    [ApiController]
    //[Authorize(Roles = "Admin")] // 只允许Admin角色访问
    public class TraineeController : ControllerBase
    {
        private readonly UserService _userService;
        private readonly SMSVerificationCodeService _smsVerificationCodeService;
        private readonly DTOBusiness _dTOBusiness;
        private readonly TokenService _tokenService;
        private readonly AppletsInterfaceBusiness _appletsInterfaceBusiness;
        private readonly UserBusiness _userBusiness;
        private readonly CourseService _courseService;
        private readonly IEncryptionService _encryptionService;
        private readonly ZenBrightBusiness _zenBrightBusiness;
        public TraineeController(UserService userService, SMSVerificationCodeService smsVerificationCodeService
           , DTOBusiness dTOBusiness, TokenService tokenService, 
            AppletsInterfaceBusiness appletsInterfaceBusiness, 
            UserBusiness userBusiness, CourseService courseService,
            IEncryptionService encryptionService, ZenBrightBusiness zenBrightBusiness
            )
        {
            _userService = userService;
            _smsVerificationCodeService = smsVerificationCodeService;
            _dTOBusiness = dTOBusiness;
            _tokenService = tokenService;
            _appletsInterfaceBusiness = appletsInterfaceBusiness;
            _userBusiness = userBusiness;
            _courseService = courseService;
            _encryptionService = encryptionService;
            _zenBrightBusiness= zenBrightBusiness;
        }
       

        /// <summary>
        /// 根据教练ID获取学员信息列表
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("GetTraineeInfoListByCoachId")]
        public async Task<ReturnObjectT<IList<UserInfoResponse>>> GetTraineeInfoListByCoachId(ReceiveObjectT<TraineeQuery2> _receiveObjectT)
        {
            ReturnObjectT<IList<UserInfoResponse>> returnObjectT = new ReturnObjectT<IList<UserInfoResponse>>();

            TraineeQuery2 _traineeQuery = _receiveObjectT.Data;

            int recordCount;
            IEnumerable<User> list = _userService.GetTraineeList(_receiveObjectT.Page, _receiveObjectT.PageSize, _traineeQuery.InstitutionId, _traineeQuery.CoachId, _traineeQuery.SearchType, _traineeQuery.SearchKey, out recordCount);
            IList<User> UserList = null;
            if (list != null)
            {
                UserList = list.ToList();
            }
            returnObjectT.Code = 1;
            List<UserInfoResponse> UserInfoResponsesList = new List<UserInfoResponse>();
            if (UserList != null && UserList.Count > 0)
            {
                for (int i = 0; i < UserList.Count; i++)
                {
                    UserInfoResponsesList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(UserList[i]));
                }
            }
            returnObjectT.RecordTotalCount = recordCount;
            returnObjectT.Data = UserInfoResponsesList;
            return returnObjectT;
        }



        /// <summary>
        /// 获取学员主子账号列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetTraineeMainSubAccountList")]
        public async Task<ReturnObjectT<IList<UserInfoResponse>>> GetTraineeMainSubAccountList(ReceiveObjectT<TraineeQuery3> _receiveObjectT)
        {
            ReturnObjectT<IList<UserInfoResponse>> returnObjectT = new ReturnObjectT<IList<UserInfoResponse>>();

            TraineeQuery3 _traineeQuery = _receiveObjectT.Data;
            int MainUserId = _traineeQuery.MainUserId;

            IList<UserInfoResponse> UserInfoResponseList = new List<UserInfoResponse>();
            User _user= await _userService.GetUserByIdAsync(MainUserId);
            UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user));


            List<User> SubUserList = await _userService.GetTraineeSubAccountList(MainUserId);
            if (SubUserList != null && SubUserList.Count > 0)
            {
                for (int i = 0; i < SubUserList.Count; i++)
                {
                    UserInfoResponseList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(SubUserList[i]));
                }
            }
            returnObjectT.Code = 1;
            returnObjectT.Data = UserInfoResponseList;
            return returnObjectT;
        }

        /// <summary>
        /// 添加学员主账号
        /// </summary>
        /// <returns></returns>
        [HttpPost("CreateTraineeMainAccount")]
        public async Task<ReturnObject> CreateTraineeMainAccount(ReceiveObjectT<CoachCreateUserRequest> _receiveObjectT)
        {
            ReturnObject _returnObject=new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            CoachCreateUserRequest coachCreateUserRequest = _receiveObjectT.Data;
            CreateUserMainAccountDTO _createUserMainAccountDTO = new CreateUserMainAccountDTO();
            _createUserMainAccountDTO.Name = coachCreateUserRequest.Name;
            _createUserMainAccountDTO.Mobile = coachCreateUserRequest.Mobile;
            _createUserMainAccountDTO.Birthday = coachCreateUserRequest.Birthday;
            _createUserMainAccountDTO.Gender = coachCreateUserRequest.Gender;

            bool isExistMobile =await _userService.ValidateMobileIsExist(_createUserMainAccountDTO.Mobile);
            if (isExistMobile)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "该手机号已存在";
                return _returnObject;
            }

            User newUser = await _userBusiness.CreateInitialTrainee(_createUserMainAccountDTO, coachCreateUserRequest.CoachId, userid);
            if (newUser == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "创建用户失败";
                return _returnObject;
            }
            else
            {
                _returnObject.Code = 1;
                return _returnObject;
            }

        }



        /// <summary>
        /// 获取可上课学员信息列表
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("GetCanAttendTraineeInfoList")]
        public async Task<ReturnObjectT<IList<UserInfoResponse>>> GetCanAttendTraineeInfoList(ReceiveObjectT<TraineeQuery> _receiveObjectT)
        {
            ReturnObjectT<IList<UserInfoResponse>> returnObjectT = new ReturnObjectT<IList<UserInfoResponse>>();

            TraineeQuery _traineeQuery = _receiveObjectT.Data;

            int recordCount;
            IEnumerable<User> list = _userService.GetTraineeList(_receiveObjectT.Page, _receiveObjectT.PageSize, _traineeQuery.InstitutionId, _traineeQuery.CourseTypeId, _traineeQuery.CoachId, out recordCount);
            IList<User> UserList = null;
            if (list != null)
            {
                UserList= list.ToList();
            }
            returnObjectT.Code = 1;
            List<UserInfoResponse> UserInfoResponsesList = new List<UserInfoResponse>();
            if (UserList != null && UserList.Count > 0)
            {
                for (int i = 0; i < UserList.Count; i++)
                {
                    UserInfoResponsesList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(UserList[i]));
                }
            }
            returnObjectT.RecordTotalCount = recordCount;
            returnObjectT.Data = UserInfoResponsesList;
            return returnObjectT;
        }

        /// <summary>
        /// 学员小程序一键登录
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("TraineeAppletLogin")]
        public async Task<ReturnObjectT<UserRegisterResponse>> TraineeAppletLogin(ReceiveObjectT<UserAppletLoginRequest> _receiveObject)
        {
            ReturnObjectT<UserRegisterResponse> _returnObject = new ReturnObjectT<UserRegisterResponse>();

            
            string code = _receiveObject.Data.Code;
            string msg;

            AppletsUserPhoneReceive appletsUserPhoneReceive = _appletsInterfaceBusiness.GetAppletsUserPhoneInfo("2", code, out msg);
            if (appletsUserPhoneReceive == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "获取手机号失败";
                return _returnObject;
            }
            if (appletsUserPhoneReceive.errcode != 0)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = appletsUserPhoneReceive.errmsg;
                return _returnObject;
            }

            string phone = appletsUserPhoneReceive.phone_info.purePhoneNumber;
           
            //根据手机号判断 用户是否已存在
            User _user = await _userService.GetTraineeByPhoneAsync(phone);
            UserRegisterResponse _userRegisterResponse = new UserRegisterResponse();

            if (_user == null)
            {
                /*
              //  _userRegisterResponse.UserIsExist = false;
                //用户不存在 则创建用户
                User newUser;
                if (!_userBusiness.CreateInitialTrainee(phone, out newUser))
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "登录失败(创建用户失败)";
                    return _returnObject;
                }
                else 
                {
                    _userRegisterResponse.UserInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(newUser);
                    _userRegisterResponse.UserToken = _tokenService.GenerateToken(newUser);
                }
                */
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户信息不存在 无法登录";
                return _returnObject;
            }
            else
            {
                //用户信息
               // _userRegisterResponse.UserIsExist = true;
                _userRegisterResponse.UserInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user);
                _userRegisterResponse.UserToken = _tokenService.GenerateToken(_user);
            }
            _returnObject.Code = 1;
            _returnObject.Data = _userRegisterResponse;
            return _returnObject;
        }

        /// <summary>
        /// 学员验证码登录
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("TraineeVerificationCodeLogin")]
        public async Task<ReturnObjectT<UserRegisterResponse>> TraineeVerificationCodeLogin(ReceiveObjectT<UserRegisterRequest> _receiveObject)
        {
            ReturnObjectT<UserRegisterResponse> _returnObjectT = new ReturnObjectT<UserRegisterResponse>();
            
            //判断验证码信息
            string phone = _receiveObject.Data.Phone;
            string code = _receiveObject.Data.VerificationCode;
            bool isSuccess = await _smsVerificationCodeService.ValidateVerificationCode(phone, code);
            if (isSuccess == false)
            {
                _returnObjectT.Code = 0;
                _returnObjectT.ErrorMsg = "验证码信息不匹配或已过期";
                return _returnObjectT;
            }
            //根据手机号判断 用户是否已存在
            
            User _user = await _userService.GetTraineeByPhoneAsync(phone);
            UserRegisterResponse _userRegisterResponse = new UserRegisterResponse();

            if (_user == null)
            {
                /*
                //  _userRegisterResponse.UserIsExist = false;
                //用户不存在 则创建用户
                User newUser;
                if (!_userBusiness.CreateInitialTrainee(phone, out newUser))
                {
                    _returnObjectT.Code = 0;
                    _returnObjectT.ErrorMsg = "登录失败(创建用户失败)";
                    return _returnObjectT;
                }
                else
                {
                    _userRegisterResponse.UserInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(newUser);
                    _userRegisterResponse.UserToken = _tokenService.GenerateToken(newUser);
                }
                */
                _returnObjectT.Code = 0;
                _returnObjectT.ErrorMsg = "用户信息不存在 无法登录";
                return _returnObjectT;
            }
            else
            {
                //用户信息
                // _userRegisterResponse.UserIsExist = true;
                _userRegisterResponse.UserInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user);
                _userRegisterResponse.UserToken = _tokenService.GenerateToken(_user);
            }
            _returnObjectT.Code = 1;
            _returnObjectT.Data = _userRegisterResponse;
            return _returnObjectT;
        }


        /// <summary>
        /// 学员信息完善
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("TraineeInfoImprove")]
        public async Task<ReturnObjectT<UserRegisterResponse>> TraineeInfoImprove(ReceiveObjectT<TraineeInfoImproveRequest> _receiveObject)
        {
            ReturnObjectT<UserRegisterResponse> _returnObject = new ReturnObjectT<UserRegisterResponse>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            User _user = await _userService.GetUserByIdAsync(userid);
            if (_user == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "获取用户信息失败";
                return _returnObject;
            }
            if (_user.UserType != ((int)UserType.Trainee).ToString())
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "您非学员账号";
                return _returnObject;
            }

            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                TraineeInfoImproveRequest _traineeInfoImproveRequest = _receiveObject.Data;
                //  if (!_traineeInfoImproveRequest.Username.IsNullOrEmpty())
                //  _user.Username = _traineeInfoImproveRequest.Username;
                if (!_traineeInfoImproveRequest.RealName.IsNullOrEmpty())
                    _user.RealName = _traineeInfoImproveRequest.RealName;
                if (!_traineeInfoImproveRequest.Gender.IsNullOrEmpty())
                    _user.Gender = _traineeInfoImproveRequest.Gender;
                if (_traineeInfoImproveRequest.InstitutionId.HasValue)
                    _user.InstitutionId = _traineeInfoImproveRequest.InstitutionId;
                if (_traineeInfoImproveRequest.CoachId.HasValue)
                    _user.CoachId = _traineeInfoImproveRequest.CoachId;
                if (!_traineeInfoImproveRequest.Password.IsNullOrEmpty())
                {
                    _user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(_traineeInfoImproveRequest.Password);
                    _user.EncryptedPassword = _encryptionService.Encrypt(_traineeInfoImproveRequest.Password);
                }
                if (_traineeInfoImproveRequest.Birthday.HasValue)
                    _user.Birthday = _traineeInfoImproveRequest.Birthday;
                if (_traineeInfoImproveRequest.AreaID > 0)
                    _user.AreaID = _traineeInfoImproveRequest.AreaID;
                if (_traineeInfoImproveRequest.Height > 0)
                    _user.Height = _traineeInfoImproveRequest.Height;
                if (_traineeInfoImproveRequest.Weight > 0)
                    _user.Weight = _traineeInfoImproveRequest.Weight;
                bool isSuccess = await _userService.UpdateUserAsync(_user);
                if (!isSuccess)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "修改信息失败";
                    return _returnObject;
                }
                UserRegisterResponse _userRegisterResponse = new UserRegisterResponse();
                _returnObject.Code = 1;
                _userRegisterResponse.UserInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user);
                _userRegisterResponse.UserToken = _tokenService.GenerateToken(_user);
                _returnObject.Data = _userRegisterResponse;

                //修改 ZenBright 系统人员数据
                ZenBrightCreateUserInfoRequest _zenBrightCreateUserInfoRequest = new ZenBrightCreateUserInfoRequest();
                _zenBrightCreateUserInfoRequest.zenSystemUserId = _user.UserId;
                _zenBrightCreateUserInfoRequest.userName = _user.Username;
                _zenBrightCreateUserInfoRequest.password = _traineeInfoImproveRequest.Password;
                _zenBrightCreateUserInfoRequest.realName = _user.RealName;
                _zenBrightCreateUserInfoRequest.gender = _user.Gender == null ? 0 : Convert.ToInt32(_user.Gender);
                _zenBrightCreateUserInfoRequest.mobile = _user.Mobile;
                _zenBrightCreateUserInfoRequest.birthday = _user.Birthday.HasValue ? _user.Birthday.Value.ToString("yyyy-MM-dd") : "";
                _zenBrightCreateUserInfoRequest.remark = "";
                bool updateZenBrightIsSuccess = await _userBusiness.UpdateZenBrightUserInfo(_zenBrightCreateUserInfoRequest);
                if (updateZenBrightIsSuccess == false)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "推送ZenBright系统失败";
                    return _returnObject;
                }
                transScope.Complete();
                _returnObject.Code = 1;
                return _returnObject;
            }
        }


        /// <summary>
        /// 获取子账号信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetSubAccountsList")]
        public async Task<ReturnObjectT<List<UserInfoResponse>>> GetSubAccountsList()
        {
            ReturnObjectT<List<UserInfoResponse>> _returnObject = new ReturnObjectT<List<UserInfoResponse>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            List<User> SubUserList = await _userService.GetTraineeSubAccountList(userid);
            List<UserInfoResponse> UserInfoResponsesList = new List<UserInfoResponse>();
            if (SubUserList != null && SubUserList.Count > 0)
            {
                for (int i = 0; i < SubUserList.Count; i++)
                {
                    UserInfoResponsesList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(SubUserList[i]));
                }
            }
            _returnObject.Code= 1;
            _returnObject.Data = UserInfoResponsesList;
            return _returnObject;
        }


        /// <summary>
        /// 学员创建子账号
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("TraineeCreateSubAccount")]
        public async Task<ReturnObject> TraineeCreateSubAccount(ReceiveObjectT<TraineeCreateSubAccountRequest> _receiveObject)
        {
            ReturnObject _returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;

            bool isSuccess = await _userBusiness.CreateSubAccount(_receiveObject.Data, userid, userid);
            if (isSuccess)
            {
                _returnObject.Code = 1;
            }
            else
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "创建子账号失败";
            }
            return _returnObject;
        }


        /// <summary>
        /// 学员更新子账号
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("TraineeUpdateSubAccount")]
        public async Task<ReturnObject> TraineeUpdateSubAccount(ReceiveObjectT<TraineeCreateSubAccountRequest> _receiveObject)
        {
            ReturnObject _returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int currentUserId = userModel.UserId;
            TraineeCreateSubAccountRequest _traineeCreateSubAccountRequest = _receiveObject.Data;
            User _user = await _userService.GetUserByIdAsync(_traineeCreateSubAccountRequest.UserId);
            if (_user == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "未获取到子账号信息";
                return _returnObject;
            }
            if (_traineeCreateSubAccountRequest.Birthday != null)
            {
                _user.Birthday = Convert.ToDateTime(_traineeCreateSubAccountRequest.Birthday);
            }
            BaseBusiness.Instance.AutoMap(_traineeCreateSubAccountRequest, _user);
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                bool saveUserIsSuccess = await _userService.UpdateUserAsync(_user);
                if (saveUserIsSuccess == false)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "保存用户数据失败";
                    return _returnObject;
                }

                TraineeCharacterRelation _traineeCharacterRelation = await _userService.GetTraineeCharacterRelationInfo(currentUserId, _user.UserId);
                if (_traineeCharacterRelation == null)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "未获取到与子账号关系信息";
                    return _returnObject;
                }
                _traineeCharacterRelation.TraineeCharacterRelationId = _traineeCreateSubAccountRequest.TraineeRelationId;
                bool saveTraineeCharacterRelationIsSuccess = await _userService.UpdateTraineeCharacterRelationAsync(_traineeCharacterRelation);
                if (saveTraineeCharacterRelationIsSuccess == false)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "保存关系数据失败";
                    return _returnObject;
                }

                //修改 ZenBright 系统人员数据
                ZenBrightCreateUserInfoRequest _zenBrightCreateUserInfoRequest = new ZenBrightCreateUserInfoRequest();
                _zenBrightCreateUserInfoRequest.zenSystemUserId = _user.UserId;
                _zenBrightCreateUserInfoRequest.userName = _user.Username;
                _zenBrightCreateUserInfoRequest.password = _encryptionService.Decrypt(_user.EncryptedPassword);
                _zenBrightCreateUserInfoRequest.realName = _user.RealName;
                _zenBrightCreateUserInfoRequest.gender = _user.Gender == null ? 0 : Convert.ToInt32(_user.Gender);
                _zenBrightCreateUserInfoRequest.mobile = _user.Mobile;
                _zenBrightCreateUserInfoRequest.birthday = _user.Birthday.HasValue ? _user.Birthday.Value.ToString("yyyy-MM-dd") : "";
                _zenBrightCreateUserInfoRequest.remark = "";
                 bool updateZenBrightIsSuccess= await _userBusiness.UpdateZenBrightUserInfo(_zenBrightCreateUserInfoRequest);
                if (updateZenBrightIsSuccess == false)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "推送ZenBright系统失败";
                    return _returnObject;
                }
                transScope.Complete();
            }
            _returnObject.Code = 1;
            return _returnObject;
        }

        /// <summary>
        /// 学员删除子账号
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("TraineeDeleteSubAccount")]
        public async Task<ReturnObject> TraineeDeleteSubAccount(ReceiveObjectT<TraineeDeleteSubAccountRequest> _receiveObject)
        {
            ReturnObject _returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int currentUserId = userModel.UserId;

            int subUserId = _receiveObject.Data.SubUserId;
            User _user = await _userService.GetUserByIdAsync(subUserId);
            if (_user == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "获取子账户信息失败";
                return _returnObject;
            }
            _user.Enabled = "0";
            bool isSuccess = await _userService.UpdateUserAsync(_user);
            if (isSuccess)
            {
                _returnObject.Code = 1;
            }
            else
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "操作失败";
            }
            return _returnObject;
        }


        /// <summary>
        /// 获取某一天的课程信息列表
        /// </summary>0
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("GetCourseListByDay")]
        public async Task<ReturnObjectT<List<Course>>> GetCourseListByDay(ReceiveObjectT<CourseQuery3> _receiveObjectT)
        {
            ReturnObjectT<List<Course>> returnObjectT = new ReturnObjectT<List<Course>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "用户未登录";
                return returnObjectT;
            }
            int userid = userModel.UserId;
            DateTime? date = null;
            if (!_receiveObjectT.Data.Date.IsNullOrEmpty())
            {
                date = Convert.ToDateTime(_receiveObjectT.Data.Date);
            }

            //获取子账号
            List<User> UserList = await _userService.GetTraineeSubAccountList(userid);
            int subTrainceCount = UserList == null ? 0 : UserList.Count;
            int[] TraineIdArr = new int[subTrainceCount + 1];
            TraineIdArr[0] = userid;
            for (int i = 0; i < UserList.Count; i++)
            {
                TraineIdArr[i + 1] = UserList[i].UserId;
            }

            IEnumerable<Course> list = await _courseService.GetCoursesListByTraineeAsync(TraineIdArr,date);
            List<Course> courseList = list.ToList();

            if (courseList != null && courseList.Count > 0)
            {
                for (int i = 0; i < courseList.Count; i++)
                {
                    courseList[i].CourseStatusTxt = ((CourseStatus)courseList[i].CourseStatus).GetDesc();
                    User _coachInfo = await _userService.GetUserByIdAsync(courseList[i].CoachId);
                    courseList[i].CoachInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_coachInfo);
                    courseList[i].CourseTypeInfo = await _courseService.GetCourseTypeByIdAsync(courseList[i].CourseTypeId);
                }
            }
            returnObjectT.Code = 1;
            returnObjectT.Data = courseList;
            return returnObjectT;
        }



       

        /// <summary>
        /// 根据时间段获取课程信息列表
        /// </summary>0
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("GetCourseListByStartEndDays")]
        public async Task<ReturnObjectT<List<Course>>> GetCourseListByStartEndDays(ReceiveObjectT<CourseQuery4> _receiveObjectT)
        {
            ReturnObjectT<List<Course>> returnObjectT = new ReturnObjectT<List<Course>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "用户未登录";
                return returnObjectT;
            }
            int userid = userModel.UserId;
            DateTime? startDate = null;
            if (!_receiveObjectT.Data.StartDate.IsNullOrEmpty())
            {
                startDate = Convert.ToDateTime(_receiveObjectT.Data.StartDate);
            }
            DateTime? endDate = null;
            if (!_receiveObjectT.Data.EndDate.IsNullOrEmpty())
            {
                endDate = Convert.ToDateTime(_receiveObjectT.Data.EndDate);
            }
            //获取子账号
            List<User> UserList = await _userService.GetTraineeSubAccountList(userid);
            int subTrainceCount = UserList == null ? 0 : UserList.Count;
            int[] TraineIdArr = new int[subTrainceCount + 1];
            TraineIdArr[0] = userid;
            for (int i = 0; i < UserList.Count; i++)
            {
                TraineIdArr[i + 1] = UserList[i].UserId;
            }

            IEnumerable<Course> list = await _courseService.GetCoursesListByTraineeAsync(TraineIdArr, startDate.Value, endDate.Value);
            List<Course> courseList = list.ToList();

            if (courseList != null && courseList.Count > 0)
            {
                for (int i = 0; i < courseList.Count; i++)
                {
                    courseList[i].CourseStatusTxt = ((CourseStatus)courseList[i].CourseStatus).GetDesc();
                    User _coachInfo = await _userService.GetUserByIdAsync(courseList[i].CoachId);
                    courseList[i].CoachInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_coachInfo);

                    courseList[i].CourseTypeInfo = await _courseService.GetCourseTypeByIdAsync(courseList[i].CourseTypeId);
                }
            }
            returnObjectT.Code = 1;
            returnObjectT.Data = courseList;
            return returnObjectT;
        }

        /// <summary>
        /// 学员取消预约课程
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("TraineeCancelReservation")]
        public async Task<ReturnObject> TraineeCancelReservation(ReceiveObjectT<TraineeCancelReservationRequest> _receiveObjectT)
        {
            ReturnObject _returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            CourseTrainee _courseTrainee =await _courseService.GetCourseTraineeByIdAsync(_receiveObjectT.Data.CourseTraineeId);
            if (_courseTrainee.AttendClassSignTime.HasValue || _courseTrainee.FinishClassSignTime.HasValue)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "该课程已正常上课,无法取消预约";
                return _returnObject;
            }

            _courseTrainee.Enabled = "0";

            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                bool cancelIsSuccess = await _courseService.UpdateCourseTraineeAsync(_courseTrainee);
                if (cancelIsSuccess == false)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "操作失败";
                    return _returnObject;
                }
                CancelReservationCourse _cancelReservationCourse = new CancelReservationCourse();
                _cancelReservationCourse.CourseTraineeId = _receiveObjectT.Data.CourseTraineeId;
                _cancelReservationCourse.CancelUserId = userid;
                _cancelReservationCourse.CancelTime = DateTime.Now;
                bool addCancelRecordIsSuccess = await _courseService.AddCancelReservationCourse(_cancelReservationCourse);
                if (addCancelRecordIsSuccess == false)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "操作失败";
                    return _returnObject;
                }
                transScope.Complete();
            }
            _returnObject.Code = 1;
            return _returnObject;
        }


        /// <summary>
        /// 发送SendZenBright测试订单
        /// </summary>
        /// <returns></returns>
        [HttpPost("SendZenBrightTestOrder")]
        public async Task<ReturnObject> SendZenBrightTestOrder(ReceiveObjectT<SendZenBrightTestOrderRequest> _receiveObjectT)
        {
            ReturnObject _returnObject=new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            LegencyUserZenUser _legencyUserZenUser = await  _userService.GetLegencyUserZenUserInfo(_receiveObjectT.Data.TraineeId);
            if (_legencyUserZenUser == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "获取ZenBright系统用户绑定信息失败";
                return _returnObject;
            }
            bool sendIsSuccess = await _zenBrightBusiness.SendDefaultTestOrder(_legencyUserZenUser.LegencyUserId, _legencyUserZenUser.ZenUserId, userid);
            if (!sendIsSuccess)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "发送失败";
                return _returnObject;
            }
            else
            {
                _returnObject.Code = 1;
            }
            return _returnObject;
        }

    }
}